package com.atguigu.lease.common.utils;

import cn.hutool.core.util.IdUtil;
import com.atguigu.lease.common.properties.MInIoProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * MinioUtils工具类
 * 用来上传文件
 *
 * @Author mr.luo
 * @Date 25 5月 2025 08:45
 */
@Slf4j
@Component
public class MinioUtils {
    @Autowired
    private MInIoProperties minIoProperties;

    public String fileUpload(MultipartFile file) throws Exception {
        String bucketName = minIoProperties.getBucketName();
        String endpoint = minIoProperties.getEndpoint();
        String accessKey = minIoProperties.getAccessKey();
        String secretKey = minIoProperties.getSecretKey();
        String url = null;
        String fileName = file.getOriginalFilename();
        try {
            // 使用 MinIO 服务器 Playground、访问地址，其访问密钥和私有密钥创建一个 minioClient。
            MinioClient minioClient = MinioClient.builder().endpoint(endpoint)
                    .credentials(accessKey, secretKey).build();
            //判断桶是否存在 如果不存在，请创建 'asiatrip' 存储桶
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket 'java-136-minio' already exists.");
            }
            String extra = fileName.substring(fileName.lastIndexOf("."));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String filePath = formatter.format(LocalDate.now());
            fileName = filePath + "/" + IdUtil.fastSimpleUUID() + extra;
            // 将 homeuserPhotosasiaphotos.zip 作为对象名称 asiaphotos-2015.zip 上传到存储桶
            // 'asiatrip'.
            minioClient.putObject(PutObjectArgs.builder().bucket("java-136-minio")
                    .object(fileName).stream(file.getInputStream(), file.getSize(), -1).build());
            //组装文件访问路径
            url = endpoint + "/" + bucketName + "/" + fileName;
            log.info("上传成功: {}", url);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return url;
    }

    //设置权限
//    public String setPolicy(String bucketName) throws Exception {
//        return """
//            {
//              "Statement" : [ {
//                "Action" : "s3:GetObject",
//                "Effect" : "Allow",
//                "Principal" : "*",
//                "Resource" : "arn:aws:s3:::%s/*"
//              } ],
//              "Version" : "2012-10-17"
//            }
//            """.formatted(bucketName);
//    }
}
